CountDownLatch 和 CyclicBarrier

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class CountDownLatchTest {

public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
for(int i = 0;i < latch.getCount();i++){
new Thread(new MyThread(latch),"player" + i).start();
}
System.out.println("等待 所所有玩家 准备好");
latch.await();
System.out.println("开始游戏");
}


private static class MyThread implements Runnable{
private CountDownLatch latch;

public MyThread(CountDownLatch latch){
this.latch = latch;
}
@SneakyThrows
@Override
public void run() {

Random rand = null;
try {
rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) +1 ) + 1000;
Thread.sleep(randomNum);
System.out.println(Thread.currentThread().getName() + "已经准备好 " + "所使用的时间是:" + randomNum );
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
for(int i = 0; i < barrier.getParties(); i++){
new Thread(new MyRunnable(barrier), "队友"+i).start();
}
System.out.println("main function is finished.");
}


private static class MyRunnable implements Runnable{
private CyclicBarrier barrier;

public MyRunnable(CyclicBarrier barrier){
this.barrier = barrier;
}

@Override
public void run() {
for(int i = 0; i < 3; i++) {
try {
Random rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) + 1) + 1000;//产生1000到3000之间的随机整数
Thread.sleep(randomNum);
System.out.println(Thread.currentThread().getName() + ", 通过了第"+i+"个障碍物, 使用了 "+((double)randomNum/1000)+"s");
this.barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
}

总结:CountDownLatch和CyclicBarrier都有让多个线程等待同步然后再开始下一步动作的意思,但是CountDownLatch的下一步的动作实施者是主线程,具有不可重复性;而CyclicBarrier的下一步动作实施者还是“其他线程”本身,具有往复多次实施动作的特点。

Donate comment here